package in.abip.chisame;

import java.io.IOException;

import org.apache.http.HttpException;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.auth.AuthState;
import org.apache.http.auth.Credentials;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.protocol.ClientContext;
import org.apache.http.impl.auth.BasicScheme;
import org.apache.http.protocol.HttpContext;

import in.abip.chisame.mjpeg.MjpegDataInputStream;
import in.abip.chisame.mjpeg.MjpegSurfaceView;
import in.abip.chisame.model.Camera;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class MjpegActivity extends Activity {
	private MjpegSurfaceView _msv;
	
	public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        setContentView(R.layout.camera_activity);
        changeTitle();
        bindHome();
        populateCamera();
	}
	
	private void populateCamera() {
		final Camera camera = getCamera();
		HttpRequestInterceptor httpRequestInterceptor = null;
		httpRequestInterceptor = new HttpRequestInterceptor() {
			public void process(
				final HttpRequest request, 
				final HttpContext context
			) throws HttpException, IOException {
				AuthState authState = (AuthState) context.getAttribute(
					ClientContext.TARGET_AUTH_STATE
				);
				
				if (authState.getAuthScheme() == null) {
					Credentials creds = new UsernamePasswordCredentials(
						camera.username,
						camera.password
					);
					if (creds != null) {
						authState.setAuthScheme(new BasicScheme());
						authState.setCredentials(creds);
					}
				}
			}
		};
		
		String url = camera.url + getRandomId();
		Log.d("URL", url);
		_msv = (MjpegSurfaceView) findViewById(R.id.video);
		_msv.setSource(MjpegDataInputStream.read(url, httpRequestInterceptor));
		_msv.setDisplayMode(MjpegSurfaceView.SIZE_BEST_FIT);
		_msv.showFps(false);
	}
	
	private String getRandomId() {
		return "&sid=" + Math.random();
	}
	
	public void onPause() {
		super.onPause();
		_msv.stopPlayback();
	}
	
	/** Change title */
	protected void changeTitle() {
		TextView text = (TextView) findViewById(R.id.title);
		text.setText(getCamera().name);
	}
	
	protected Camera getCamera() {
		Bundle bundle = getIntent().getExtras();
		Integer cameraId = bundle.getInt("cameraId");
		Camera camera = (Camera) Camera.model().findByPk(cameraId);
		return camera;
	}
	
	/** Bind home button click. */
	protected void bindHome() {
		OnClickListener listener = new OnClickListener() {
			public void onClick(View view) {
				MjpegActivity.this.finish();
			}
		};
		View view = (View) findViewById(R.id.home);
		view.setOnClickListener(listener);
	}
}
